const Base = require('../../base.js');

module.exports = class extends Base {
  async indexAction() {
    let data = this.post()
    // 1.判断是否获取验证码
    let sms_code = await this.session('sms_code')
    
    if (!sms_code) {
      return this.fail(-1, '请先获取验证码')
    }
    console.log('已获取验证码')
    // 2.判断验证码是否过期
    if (sms_code.time < Date.now()) {
      return this.fail(-1, '验证码已失效')
    }
    console.log('验证码未失效')
    // 3.判断验证码 手机号是否正确
    if (data.phone != sms_code.phone || data.code != sms_code.code) {
      return this.fail(-1, '验证码不正确')
    }
    console.log('验证码正确')
    let result = await this.model('user/index').register(data)
    console.log('注册结果', result)
    if (typeof result == 'string') {
      return this.fail(-1, result || '系统异常')
    }
    let user_info = JSON.parse(JSON.stringify(result))
    console.log('格式化用户信息', user_info)
    let token = await this.session('user_info', user_info)
    console.log('生成token', token)
    this.json({
      status: 200, message: '注册成功',
      data: {
        user: user_info,
        token
      }
    })
  }
};
